package m.jclecai.com.activity;


import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.ProofBean;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.ChannelUtil;
import m.jclecai.com.utils.MD5;
import m.jclecai.com.utils.MyToast;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 *  注册
 */
public class RegisterActivity extends BaseActivity {

    /**
     * 判断是否绑定了手机号；
     */
    boolean hasBindPhoneNumber=false;

    @BindView(R.id.et_name)
    EditText mEtName;

    @BindView(R.id.et_receive_prize)
    EditText mEtReceivePrize;

    @BindView(R.id.iv_clear_phone)
    ImageView mIvClearPhone;

    @BindView(R.id.et_graph_code)
    EditText mEtGraphCode;

    @BindView(R.id.iv_gf)
    ImageView mIvGf;

    @BindView(R.id.et_auth_code)
    EditText mEtAuthCode;

    @BindView(R.id.tv_send_proof)
    TextView mTvSendProof;

    @BindView(R.id.ll_next)
    LinearLayout mLlNext;

    @BindView(R.id.et_user)
    EditText mEtUser;

    @BindView(R.id.et_password)
    EditText mEtPassword;

    @BindView(R.id.ll_regist)
    LinearLayout mLlRegist;

    @BindView(R.id.tv_pact)
    TextView mTvPact;

    @BindView(R.id.text_bottom)
    TextView mTextBottom;

    @BindView(R.id.tv_reg)
    TextView mTvReg;

    private static String IS_BIND_PHONE_NUMBER = "isBindPhoneNumber";

    private Map<String,String> pairms;
    private boolean mIsWeiXin;

    @OnClick(R.id.tv_pact)
    public void onClickPack(){
        startActivity(LotteryProtocolActivity.getIntent(this));
    }
    @Override
    public int getContentView() {
        return R.layout.activity_register;
    }

    @Override
    protected void initView() {
        super.initView();
        leftOptionText("");
        setTitle("注册");
    }


    @Override
    protected void initData() {
        //这里我们要实现的逻辑就是；
        boolean isBindPhoneNumber = getIntent().getBooleanExtra(IS_BIND_PHONE_NUMBER, true);
        mIsWeiXin = getIntent().getBooleanExtra(IS_WEI_XIN, false);

        hasBindPhoneNumber=!isBindPhoneNumber;

        showBindPhoneNumber(isBindPhoneNumber); //初始化页面；
        //这里的话，我们同样是需要获取相应的参数；
        pairms = FastOk.get(getIntent().getStringExtra("param"), new TypeReference<Map<String, String>>() {});

        getImgCode();
    }

    public static String IS_WEI_XIN="isWeiXin";
    public static String WEI_XIN_DATA="weiXinData";


    public static Intent getIntent(Context context, boolean isBindPhoneNumber, boolean isWeiXin,Bundle data) {
        Intent intent = new Intent(context, RegisterActivity.class);
        intent.putExtra(IS_BIND_PHONE_NUMBER, isBindPhoneNumber);
        intent.putExtra(IS_WEI_XIN, isWeiXin);
        intent.putExtra(WEI_XIN_DATA, data);
        return intent;
    }

    /**
     * 这里是获取一个Intent的
     * @param context
     * @param isBindPhoneNumber
     * @return
     */
    public static Intent getIntent(Context context, boolean isBindPhoneNumber) {
        Intent intent = new Intent(context, RegisterActivity.class);
        intent.putExtra(IS_BIND_PHONE_NUMBER, isBindPhoneNumber);
        return intent;
    }

    /**
     * 这里表示是否显示phoneNumber;
     *
     * @param isShow
     */
    public void showBindPhoneNumber(boolean isShow) {

        int showReg = isShow ? View.GONE : View.VISIBLE;
        mLlRegist.setVisibility(showReg);
        mTvReg.setVisibility(showReg);

        int showNext = isShow ? View.VISIBLE : View.GONE;
        mLlNext.setVisibility(showNext);
        mTextBottom.setVisibility(showNext);

        if (isShow){
            setTitle("绑定手机号");
        }else{
            setTitle("设置");
        }
    }

    @OnClick({R.id.text_bottom, R.id.tv_reg})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text_bottom:
                //这里我们实现绑定手机号的逻辑
                onNextClick();
                break;
            case R.id.tv_reg:
                //实现注册的逻辑
                onRegisterClick();
                break;
        }
    }

    //图形验证码
    @OnClick(R.id.iv_gf)
    void getImgCode() {
        Glide.with(this)
                .load(Constant_Url.REGISTER_RAND_URL)
                .diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
                .skipMemoryCache(true).into(mIvGf);//跳过内存缓存
    }


    /**
     * 注册用户名字；
     */
    private void onRegisterClick() {


        final String userName = mEtUser.getText().toString();
        final String password = mEtPassword.getText().toString();

        Observable.just(true)
        .flatMap(new Func1<Boolean, Observable<Boolean>>() {
            @Override
            public Observable<Boolean> call(Boolean o) {
                return checkRegisterInputValid(userName,password);
            }
        }) .flatMap(new Func1<Boolean, Observable<Boolean>>() {
            @Override
            public Observable<Boolean> call(Boolean aBoolean) {
                return registerUser(userName,password);
            }
        }).subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Boolean>() {
            @Override
            public void onStart() {
                showDialog();
            }
            @Override
            public void onCompleted() {
                dissDialog();
                //这里我们执行登陆的逻辑：
                login(mEtUser.getText().toString(),mEtPassword.getText().toString(),true);
            }

            @Override
            public void onError(Throwable e) {
                dissDialog();
                if (e instanceof RuntimeException) {
                    DisPlay(((RuntimeException) e).getMessage());
                }else {
                    DisPlay("请检查网络！！！");
                }

                e.printStackTrace();
            }

            @Override
            public void onNext(Boolean aBoolean) {
                System.out.println("onNext: "+aBoolean);
            }
        });
        /*
        这里我们可以明显看到采用Rx的好处，就是代码逻辑清晰，
        这里我们想要去掉登陆的逻辑，在这里实现就可以了
        */
    }

    /**
     * 检查用户名和密码的合理性；
     * @param userName
     * @param password
     */
    private Observable checkRegisterInputValid(String userName, String password) {
        if (TextUtils.isEmpty(userName)) {
            return Observable.error(new RuntimeException("用户名不能为空哦!"));
        }
        if (userName.length() < 4 || userName.length() > 16) {
            return Observable.error(new RuntimeException("用户名长度为4-16位字符!"));
        }
        if (TextUtils.isEmpty(password)) {
            return Observable.error(new RuntimeException( "密码不能为空哦!"));
        }
        if (password.length() < 6 || password.length() > 20) {
            return Observable.error(new RuntimeException("密码长度为6-20位字符!"));
        }
        return Observable.just(true);
    }

    /**
     * 重新注册用户名和密码；
     * @param username
     * @param password
     * @return
     */
    private Observable registerUser(String username,String password) {
        //这里我们要进行一个操作就是重置用户名和密码；

        HashMap<String, String> pairm = new HashMap<>();
        pairm.put("name",username);
        pairm.put("newValue",password);
        pairm.put("user",pairms.get("user"));
        pairm.put("password",pairms.get("password"));

        String strResponse = "";
        try {
            strResponse = HttpManager.postAsString(Constant_Url.SETNAME, pairm);
        } catch (IOException e) {
            e.printStackTrace();
            return Observable.error(new RuntimeException("网络异常！！！"));
        }

        ProofBean proofBean = FastOk.get(strResponse, ProofBean.class);
        if (proofBean != null) {
            if (!"0".equals(proofBean.getStatus())) {
                //存在此用户名，跳转
                return Observable.error(new RuntimeException(proofBean.getMessage()));
            } else {
                //这里表示成功；
                return Observable.just(true);
            }
        } else {
            return Observable.error(new RuntimeException("网络异常！！！"));
        }
    }

    /**
     * 这里我们要做的逻辑就绑定手机号；
     */
    private void onNextClick() {

        String recommendPerson = mEtName.getText().toString().trim();       //推荐人
        String phoneNumber = mEtReceivePrize.getText().toString().trim();   //手机号
        String graphCode = mEtGraphCode.getText().toString().trim();//请输入图形验证码
        String phoneNumberCode = mEtAuthCode.getText().toString().trim();   //手机验证码

        checkInputValid(recommendPerson, phoneNumber, graphCode, phoneNumberCode);

        bindPhoneNumber(recommendPerson, phoneNumber, graphCode, phoneNumberCode);

    }

    /**
     * 验证绑定手机号的有效性
     * @param recommendPerson
     * @param phoneNumber
     * @param graphCode
     * @param phoneNumberCode
     */
    private void checkInputValid(String recommendPerson,String phoneNumber,String graphCode,String phoneNumberCode) {

        if (TextUtils.isEmpty(phoneNumber) || !BaseUtils.isMobileNO(phoneNumber)) {
            MyToast.showToast(this, "请输入正确的手机号码");
            return;
        }
        if (TextUtils.isEmpty(graphCode)) {
            MyToast.showToast(this, "请输入图形验证码");
            return;
        }
        if (TextUtils.isEmpty(phoneNumberCode)) {
            MyToast.showToast(this, "请输入手机验证码");
            return;
        }
    }

    /**
     * 绑定手机号；
     * @param recommendPerson
     * @param phoneNumber
     * @param graphCode
     * @param phoneNumberCode
     */
    private void bindPhoneNumber(String recommendPerson, String phoneNumber, String graphCode, String phoneNumberCode) {

        final HashMap<String, String> pair = new HashMap<>();
        pair.put("vphone", phoneNumberCode);//短信验证码
        pair.put("sessionid", graphCode);//图形验证码
        pair.put("phone", phoneNumber);//手机号码
        pair.put("parentName", recommendPerson);//推荐人姓名
        pair.put("flag", "4");//标志flag=2 (修改密码)flag=3 (绑定手机)flag=4 (修改并绑定手机)
        pair.put("user",pairms.get("user"));
        pair.put("password",pairms.get("password"));

        Observable.just(true)
                .flatMap(new Func1<Boolean, Observable<ProofBean>>() {
            @Override
            public Observable<ProofBean> call(Boolean aBoolean) {

                //绑定手机号；
                return bindPhoneNumber(pair);
            }
        }).flatMap(new Func1<ProofBean, Observable<Boolean>>() {
            @Override
            public Observable<Boolean> call(ProofBean aBoolean) {

                //这里表示绑定手机号成功；
                hasBindPhoneNumber=true;

                //这里我们要做的操作，判断是否登陆了设置了用户名；
                //请求网络
                HashMap<String, String> map = new HashMap<>();
                map.put("user",pairms.get("user"));
                map.put("password",pairms.get("password"));
                return isRegisterUserName(map);
            }
        }).observeOn(AndroidSchedulers.mainThread())
        .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Boolean>() {
                    boolean isRegister=false;
                    @Override
                    public void onStart() {
                        showDialog();
                    }

                    @Override
                    public void onCompleted() {
                        dissDialog();
                        if(isRegister){
                            //这里表示用户名不为空已经注册过了
                            //登陆的逻辑；
                            login(pairms.get("user"),pairms.get("password"),false);
                        }else{
                            showBindPhoneNumber(false);
                        }

                        PreferenceUtil.writeBoolean(RegisterActivity.this,PreferenceUtil.WEI_XIN_IS_BIND_PHONE_NUMBER,true);
                    }

                    @Override
                    public void onError(Throwable e) {
                        dissDialog();
                        if (e instanceof RuntimeException) {
                            DisPlay(e.getMessage());
                        }else{
                            DisPlay("网络异常！！！");
                        }
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                            isRegister=aBoolean;
                    }
                });

    }


    public void login(final String user, final String password, boolean isEntry){

        logIn(user, password, isEntry,new m.jclecai.com.listener.Callback() {
            @Override
            public void callbackSuccess() {
                super.callbackSuccess();
                PreferenceUtil.writeBoolean(RegisterActivity.this,PreferenceUtil.IS_USER_NAME_EMPTY,false);
                Intent intent = new Intent();
                intent.putExtra("user",user);
                intent.putExtra("password", MD5.getMD5(password));
                setResult(Activity.RESULT_OK,intent);
                finish();
            }

            @Override
            public void callbackField() {
                super.callbackField();
                DisPlay("登录失败请尝试手动登录！");
            }
        });

    }


    /**
     * 检查手机号；
     * @param pair
     * @return
     */
    private Observable<ProofBean> bindPhoneNumber(HashMap<String, String> pair) {

        String responseStr="";
        pair.put("appstore", ChannelUtil.getChannel());
        try {
            responseStr = HttpManager.postAsString(Constant_Url.CHECK_PHONE_RANDNUM_URL, pair);

            if (!TextUtils.isEmpty(responseStr)) {
                // ProofBean
                ProofBean proofBean = FastOk.get(responseStr, ProofBean.class);
               if (proofBean != null) {
                    if (proofBean.getStatus().equals("0")) {
                        //这里的话，我们要做一个判断是否重新设置了用户名，如果是的话，这里我们就直接登陆，如果没有的话，我们就，需要设置用户名和密码
                        return Observable.just(proofBean);
                    }else{
                        return Observable.error(new RuntimeException(proofBean.getMessage()));
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Observable.error(new RuntimeException("网络异常！！！"));
    }


    //发送验证码
    @OnClick(R.id.tv_send_proof)
    void sendProof() {
        if(mIsWeiXin){
            //这里表示微信绑定手机号的时候发送验证码，
            sendWeiXinProofCode();
        }else {
            //这里表示普通绑定手机号的时候发送验证码；
            sendProofCode();
        }
    }

    /**
     * 这里是发送普通的验证码
     */
    private void sendProofCode() {

        String phone = mEtReceivePrize.getText().toString().trim();
        if (TextUtils.isEmpty(phone) || !BaseUtils.isMobileNO(phone)) {
            MyToast.showToast(RegisterActivity.this, "请输入正确的手机号码");
            return;
        }
        BaseUtils.countDowm(RegisterActivity.this, 60, mTvSendProof);
        HashMap<String, String> pair = new HashMap<>();
        pair.put("phone", phone);
        HttpManager.postAsyn(Constant_Url.PROOF_URL, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                MyToast.showToast(RegisterActivity.this, "验证码发送失败");
            }

            @Override
            public void onResponse(String response) {
                ProofBean proofBean = FastOk.get(response, ProofBean.class);
                if (proofBean != null)
                    //MyToast.showToast(RegisterActivity.this, proofBean.getMessage());
                    DisPlay(proofBean.getMessage());
                else
                    DisPlay("网络异常！！！");
                //MyToast.showToast(RegisterActivity.this, getString(R.string.error_network));

            }
        }, pair);

    }

    /**
     * 这里是发送微信绑定手机号的时候发送验证码
     */
    private void sendWeiXinProofCode() {

        String phone = mEtReceivePrize.getText().toString().trim();
        String graphCode = mEtGraphCode.getText().toString();
        if (TextUtils.isEmpty(phone) || !BaseUtils.isMobileNO(phone)) {
            MyToast.showToast(RegisterActivity.this, "请输入正确的手机号码");
            return;
        }
        if(TextUtils.isEmpty(graphCode)){
            MyToast.showToast(RegisterActivity.this, "图形验证码不能为空！！！");
            return;
        }
        Bundle bundleExtra = getIntent().getBundleExtra(WEI_XIN_DATA);

        BaseUtils.countDowm(RegisterActivity.this, 60, mTvSendProof);
        HashMap<String, String> pair = new HashMap<>();
        pair.put("phone", phone);
        pair.put("user", bundleExtra.getString("user"));
        pair.put("sessionid", graphCode);
        pair.put("password", bundleExtra.getString("password"));
        HttpManager.postAsyn(Constant_Url.WEI_BIND_PHONE_NUMBER, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                MyToast.showToast(RegisterActivity.this, "验证码发送失败");
            }

            @Override
            public void onResponse(String response) {
                ProofBean proofBean = FastOk.get(response, ProofBean.class);
                if (proofBean != null)
                    //MyToast.showToast(RegisterActivity.this, proofBean.getMessage());
                    DisPlay(proofBean.getMessage());
                else
                    DisPlay("网络异常！！！");
                //MyToast.showToast(RegisterActivity.this, getString(R.string.error_network));

            }
        }, pair);


    }


    @Override
    public void onBackPressed() {
        //这里表示用户将没有完成点击了返回按键
        boolean isFromBindPhone = !TextUtils.isEmpty(getIntent().getStringExtra("from"));
        if (isFromBindPhone) {
            //这里表示从绑定手机号那里进来的
            if (hasBindPhoneNumber) {
                setResult(RESULT_OK);
                super.onBackPressed();
            }else{
                new AlertDialog.Builder(this)
                        .setMessage("退出将重新登陆!!!")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                }).show();

            }
        }else{
            super.onBackPressed();
        }
    }

    @Override
    protected void close() {
        onBackPressed();
    }

    public Observable<Boolean> isRegisterUserName(HashMap<String,String> map) {
        //这里我判断是否之前重新设置过了用户名和密码；
        String responseStr="";
        try {
            responseStr = HttpManager.postAsString(Constant_Url.GET_USER_INFO, map);
            if(!TextUtils.isEmpty(responseStr)){
                UserBean userBean = FastOk.get(responseStr, UserBean.class);
                if ("0".equals(userBean.getStatus())) {
                    //String username = userBean.getUsername();

                    JSONObject jsonObject = JSON.parseObject(responseStr);
                    String username = jsonObject.getString("username");

                    if(!TextUtils.isEmpty(username)){
                        //这里表示没有设置过用户名和密码；
                        return Observable.just(true);
                    }else{
                        return Observable.just(false);
                    }
                }else{
                    return Observable.error(new RuntimeException(userBean.getMessage()));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Observable.error(new RuntimeException("网络异常!!!"));
    }
}
